package cn.ug.account.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.*;


public class WxService {

    private static Logger logger = LoggerFactory.getLogger(WxService.class);

    /**
     * 第一步，获取token
     * @return
     */
    public static String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WxConfig.APPID+"&secret="+WxConfig.APPSECRET+"";
        String resultStr = WxPayUtil.sendHttp(url, "GET", null);
        JSONObject json = JSONObject.parseObject(resultStr);
        logger.info("---第一步----"+json.toString());
        return json.get("access_token").toString();
    }

    /**
     * 第二步，获取jsapi_ticket
     * @param accessToken
     * @return
     */
    public static String getJsapiTicket(String accessToken){
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        String resultStr = WxPayUtil.sendHttp(url, "GET", null);
        JSONObject json = JSONObject.parseObject(resultStr);
        logger.info("---第二步----"+json.toString());
        return json.get("ticket").toString();
    }

    /**
     * 第三步，获取签名数据
     * @return
     */
    public  static Map<String,Object> getShareSign(String url){
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String jsapiTicket = getJsapiTicket(getAccessToken());
        Date dt = new Date();
        String timestamp = String.valueOf(dt.getTime()/1000);
        String noncestr = WxPayUtil.GenerateNonceStr(8);
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("jsapi_ticket", jsapiTicket);
        param.put("timestamp", timestamp);
        param.put("noncestr", noncestr);
        param.put("url", url);
        try{
            String signatureStr  = "jsapi_ticket=" + jsapiTicket +
                    "&noncestr=" + noncestr +
                    "&timestamp=" + timestamp +
                    "&url=" + url;
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(signatureStr.getBytes("UTF-8"));
            String signature = byteToHex(crypt.digest());
            param.put("signature", signature);
            //param.put("signature", SHA1.getSha1(param).toLowerCase());
        }catch (Exception e){
        }
        param.put("appId", WxConfig.APPID);
        logger.info("---第三步----"+param.toString());
        return param;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)  {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static void main(String[] args) {
        System.out.println(getAccessToken());
    }
}
